package deibay.server.frontend.communication.clients;

import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.messages.Message;
import deibay.server.commands.Command;
import deibay.server.frontend.FrontEndCore;
import deibay.users.User;
import deibay.util.IClosable;
import deibay.util.Pair;

public class MessageConsumer implements Runnable, IClosable{

	private BlockingQueue<Pair<User, Message>> messageQueue = null;	
	private boolean keepAlive;

	public MessageConsumer(BlockingQueue<Pair<User, Message>> messageQueue)
	{
		this.messageQueue = messageQueue;
		keepAlive = true;
	}

	public void run() {
		while(keepAlive == true)
		{			
			
			Pair<User, Message> pair;
			try {
				pair = messageQueue.take();
				User user = pair.getFirst();
				Message message = pair.getSecond();				
				Command command = Command.parse(message, user);
				DeibayLogger.getInstance().getLog().log(Level.INFO, "Processando mensagem: " +message.toString()+".\n");
				command.execute();
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}

		}					
	}	
	
	public void close() {
		keepAlive = false;		
	}
}
